package com.xbb.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseUtil {
  Connection connection;
  Configuration conf;

  private HBaseUtil() throws IOException {
    conf = HBaseConfiguration.create();
    connection = ConnectionFactory.createConnection(conf);
  }

  private static HBaseUtil instance = null;

  public static synchronized HBaseUtil getInstance() throws IOException {
    if (instance == null) {
      instance = new HBaseUtil();
    }
    return instance;
  }

  public Table getTable(String tableName) throws IOException {
    return connection.getTable(TableName.valueOf(tableName));
  }

  public void put(String tableName, String rowKey, String columnFamily, String column, String value) throws IOException {
    Table table = getTable(tableName);
    Put put = new Put(Bytes.toBytes(rowKey));
    put.addColumn(
            Bytes.toBytes(columnFamily),
            Bytes.toBytes(column),
            Bytes.toBytes(value)
    );
    table.put(put);
    table.close();
  }


  public static void main(String[] args) throws IOException {
    // HTable table = HBaseUtil.getInstance().getTable("imooc:course");
    // System.out.println(table.getName().getNameAsString());
    HBaseUtil.getInstance().put(
            "imooc:course",
            "20200516_138",
            "info",
            "click_count",
            "23"
    );
  }
}
